#!/usr/bin/env python
# coding=utf-8
# 
import MySQLdb
import ConfigParser
import json
import requests
import hashlib
import traceback
import time
import redis
from utils.syslog import Logger
from utils.EmailUtil import send_mail

config = ConfigParser.ConfigParser()
config.read("./conf/config.ini")
print config.get("mysqldb", "host")
logger = Logger(logger="log").getlog()

redis_poll = redis.ConnectionPool(host=config.get("redis", "REDIS_SERVER"),port=config.get("redis", "REDIS_PORT"), db=config.get("redis", "REDIS_DB"))
redis_con = redis.Redis(connection_pool = redis_poll)

global conn
def  getConn():
	conn= MySQLdb.connect(
	        host=config.get("mysqldb", "host"),
	        port = int(config.get("mysqldb", "port")),
	        user=config.get("mysqldb", "user"),
	        passwd=config.get("mysqldb", "passwd"),
	        db =config.get("mysqldb", "db"),
	        charset="utf8"
	        )
	return conn


def sendPackage(openid, sourceid, bonus):
	
	postParams = {
		'openid': openid,
		'mount' : bonus*100,
		'checkcode' : '0aBb04a920294c589f2ae8ca2Cd36f8E' #验证码
	}
	
	headers = {"content-type": "application/x-www-form-urlencoded; charset=utf-8"}
	print '*****************'
	logger.info('发红包数据：' + json.dumps(postParams, indent=4)) 
	print '==========================='
	try:
		url = 'http://nianhui.vcanbio.com/VcanbioNh/index/redpackage/sendbyopenid.html'
		validRes = requests.post(url, data = postParams, headers = headers, verify = False)
		# resStr = json.JSONDecoder().decode(validRes.text)
		# print validRes
		# logger.info('发红包反馈数据：' + validRes.text)
		if str(validRes.status_code) == '200' :
			# validResJson = json.JSONDecoder().decode(validRes.text)
			# print validResJson
			validResDict = json.loads(validRes.text)
			validStatusCode = str(validResDict['code'])
			if validStatusCode == '1' :
				count = 0
				while (count < 5):
					try:
						cur.execute("update nh_passwd_source set is_used=1,open_id='"+openid+"' where oid = '"+sourceid+"'")
						conn.commit()
						break
					except Exception:
						conn.rollback()
						count = count + 1
						logger.error('更新红包状态失败：'+ openid + "，异常信息："+traceback.format_exc())
				if count >= 5:
					send_mail('更新红包出错，请尽快处理！openid：' + openid + ",sourceid：" + sourceid)
					logger.error('更新红包状态尝试5次后失败：'+ openid)
		# print checkStr
	except Exception:
		logger.error('更新红包状态失败：'+ openid + "，异常信息："+traceback.format_exc())

if __name__ == '__main__':
	logger.info('********程序启动********')
	
	while True:
		try:
			conn = getConn()
			cur = conn.cursor()
			print 'connect database'
			qsize = redis_con.llen("password_list")
			while qsize > 0:
				
				listuser = redis_con.lpop("password_list")
				if listuser:
					logger.info('****查询到数据*******'+str(listuser))
					userarr = listuser.split('@')
					if len(userarr) == 3:
						#验证人员是否为受邀人员（现场、非现场）
						statusSql = "select count(*) from nh_personnel p WHERE p.personnel_type!=2 AND p.open_id='"+userarr[0]+"' "
						cur.execute(statusSql)
						statusRow = cur.fetchone()
						if statusRow[0] > 0: 
							sql = "select s.oid, MAX(s.bonus) from nh_passwd_source s \
								where s.passwd='"+userarr[1]+"' and (s.open_id ='no') \
								and (SELECT COUNT(*) from nh_passwd_source where passwd='"+userarr[1]+"' \
								and  open_id ='"+userarr[0]+"' and is_used = 1)=0 "
							logger.info('****userarr*******'+sql)
							cur.execute(sql)
							results = cur.fetchall()
							for row in results: 
							    logger.info('****不应该到这里*******' + str(userarr[0])+'===='+ str(row[0]))
							    if row==None or row[0]==None or row[1]==None:
							    	continue
							    sendPackage(str(userarr[0]), str(row[0]), float(row[1]))
						else:
							logger.info('****非受邀用户*******'+str(listuser))
				qsize = qsize - 1;
			conn.close()
			time.sleep(10)
		except Exception:
			print '==='
			logger.error('save error'+traceback.format_exc())
			send_mail('发红包程序运行出错，请尽快处理！'+traceback.format_exc())
			break
			# if conn is not None:
				# conn.close()
	#创建数据表
	#cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")

	#插入一条数据
	#cur.execute("insert into student values('2','Tom','3 year 2 class','9')")


	#修改查询条件的数据
	#cur.execute("update student set class='3 year 1 class' where name = 'Tom'")

	#删除查询条件的数据
	#cur.execute("delete from student where age='9'")

	#aa=cur.execute("select * from wxpay_order where id<6 ")
	# 打印数据条数
	#print aa
	#打印所有数据方法1
	# for i in range(0, aa):
	# 	#游标一条一条打印
	# 	print cur.fetchone()
	# 	
	#打印所有数据方法2
	

	print "=============================="
	#打印所有数据方法3
	# info = cur.fetchmany(aa)
	# for ii in info:
	#     print ii

	#打印所有数据方法4
	# rows = cur.fetchall()  
	# for row in rows:  
	#     print "%d, %s, %s, %s" % (row[0], row[1], row[2], row[3]) 

	# recharge('80102000000566', '888888', '20161112', '205300', '1478955228','0.01','')

	